/*
* Copyright (C) 2012 Manuel Pérez
*
* This file is part of OpenSudoku.
*
* OpenSudoku is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* OpenSudoku is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with OpenSudoku. If not, see <http://www.gnu.org/licenses/>.
*
*/
package igraf.kontsultak;

import igraf.ItzuliInterfazea;
import igraf.Panela;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.SystemColor;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.sql.SQLException;
import java.text.ParseException;
import java.util.List;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFormattedTextField;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.text.MaskFormatter;

import modeloa.Bezero;
import modeloa.BezeroModeloa;
import dBasea.Bezeroa;

public class PanelKontsulta extends Panela{
	private static final long serialVersionUID = -4814370122593505507L;
	private JButton atzera;
	private JPanel panel;
	private JLabel bilatu;
	private JComboBox aukeratu;
	private JLabel bilaketa;
	private JTextField bil;
	private JButton btnBilatu;
	private JLabel lblNewLabel;
	private JTextField nan;
	private JLabel lblNewLabel_1;
	private JTextField izena;
	private JLabel lblNewLabel_2;
	private JTextField abi;
	private JLabel lblNewLabel_3;
	private JTextField helb;
	private JLabel lblNewLabel_4;
	private JTextField tele;
	private JLabel lblNewLabel_5;
	private JComboBox aseg;
	private JButton btnGorde;
	private JButton btnKendu;
	private JButton btnEguneratu;
	private JButton btnEzeztatu;
	private JButton btnBerria;
	private BezeroModeloa bm;
	private JTable table;
	private Bezeroa beze= new Bezeroa();
	
	
	public PanelKontsulta(String tituloa, final ItzuliInterfazea itzuliInterfazea) {
		super(tituloa);
		JPanel erdikoPanela = this.getErdikoPanela();
		erdikoPanela.setBackground(SystemColor.activeCaption);
		erdikoPanela.setLayout(new BorderLayout());
	
		bm = new BezeroModeloa();
		table = new JTable(bm);
		table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		

		
		panel = new JPanel();
		panel.setBackground(SystemColor.activeCaption);
		panel.setLayout(new GridLayout(5,1));
		erdikoPanela.add(panel);
		JPanel bat= new JPanel();
		bat.setBackground(SystemColor.activeCaption);
		FlowLayout fl_arri = new FlowLayout();
		fl_arri.setHgap(15);
		fl_arri.setVgap(10);
		 bat.setLayout(fl_arri);
		bilatu=new JLabel("Aukeratu kontsulta:");
		bilatu.setFont(new Font("Arial", Font.PLAIN, 14));
		aukeratu = new JComboBox();
		aukeratu.addItem("NAN");
		aukeratu.addItem("Izena");
		aukeratu.addItem("Abizenak");
		aukeratu.addItem("Helbidea");
		aukeratu.addItem("Telefonoa");
		aukeratu.addItem("Asegurua");
		
		bat.add(bilatu);
		bat.add(aukeratu);
		
		panel.add(bat);
		
		JPanel lau = new JPanel();
		lau.setBackground(SystemColor.activeCaption);
		FlowLayout fl_lau = new FlowLayout();
		fl_lau.setHgap(15);
		fl_lau.setVgap(7);
		lau.setLayout(fl_lau);
		bilaketa=new JLabel("Bilatzekoa:");
		bilaketa.setFont(new Font("Arial", Font.PLAIN, 14));
		bil=new JTextField(20);
		lau.add(bilaketa);
		lau.add(bil);
		btnBilatu = new JButton("Bilatu");
		btnBilatu.setIcon(new ImageIcon(PanelKontsulta.class.getResource(("/Argazkia/lupita.png"))));
		lau.add(btnBilatu);
		panel.add(lau);
		
		JPanel aux = new JPanel();
		aux.setBackground(SystemColor.activeCaption);
		aux.setLayout(new FlowLayout());
		JPanel auxx = new JPanel(new GridLayout(3, 2));
		JPanel aux2 = new JPanel(new FlowLayout());
		aux2.setBackground(SystemColor.activeCaption);
		aux2.add(auxx);
		panel.add(aux2);
		
		auxx.setBackground(SystemColor.activeCaption);

		lblNewLabel = new JLabel("NAN");
		auxx.add(lblNewLabel);
		
		nan = new JTextField();
		auxx.add(nan);
		nan.setColumns(7);
		
		lblNewLabel_1 = new JLabel("Izena");
		auxx.add(lblNewLabel_1);
		
		izena = new JTextField();
		auxx.add(izena);
		izena.setColumns(7);
		
		lblNewLabel_2 = new JLabel("Abizenak");
		auxx.add(lblNewLabel_2);
		
		abi = new JTextField();
		auxx.add(abi);
		abi.setColumns(8);
		
		lblNewLabel_3 = new JLabel("Helbidea");
		auxx.add(lblNewLabel_3);
		
		helb = new JTextField();
		auxx.add(helb);
		helb.setColumns(9);
		
		lblNewLabel_4 = new JLabel("Telefonoa");
		auxx.add(lblNewLabel_4);
		
		try {
			tele = new JFormattedTextField(new MaskFormatter("#########"));
		} catch (ParseException e2) {
			e2.printStackTrace();
		}
		auxx.add(tele);
		tele.setColumns(6);
		
		lblNewLabel_5 = new JLabel("Asegurua");
		auxx.add(lblNewLabel_5);
		
		aseg = new JComboBox();
		auxx.add(aseg);
		try {
			List<String> motak = beze.getAseguruTipoDeskripzioa();
			if (motak != null) {
				for (String m: motak) {
					aseg.addItem(m);
				}
			}
		}
		catch (SQLException e1) {
			e1.printStackTrace();
		}
		
		JPanel ajj = new JPanel();
		ajj.setBackground(SystemColor.activeCaption);
		ajj.setLayout(new FlowLayout());
		panel.add(ajj);
		
		btnBerria = new JButton("Berria");
		btnBerria.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				btnGorde.setEnabled(true);
		        btnBerria.setEnabled(false);
		        btnEzeztatu.setEnabled(true);
		        btnKendu.setEnabled(false);
		        btnEguneratu.setEnabled(false);
		        eremuakGarbitu();
			}
		});
		ajj.add(btnBerria);
		
		btnGorde = new JButton("Gorde");
		
		
		ajj.add(btnGorde);
		
		table.getSelectionModel().addListSelectionListener(new ListSelectionListener() {			
			@Override
			public void valueChanged(ListSelectionEvent lse) {
				if (lse.getValueIsAdjusting()) {
					ListSelectionModel rowSM = (ListSelectionModel)lse.getSource();
					int row = rowSM.getMinSelectionIndex();

					if (row != -1) {
						btnEguneratu.setEnabled(true);
			            btnBerria.setEnabled(false);
			            btnGorde.setEnabled(false);
			            btnKendu.setEnabled(true);
			            btnEzeztatu.setEnabled(true);
			            Bezero dc = bm.getFila(row);
			            nan.setText(dc.getNAN());  
			            izena.setText(dc.getIzena());
			            abi.setText(dc.getAbizenak());
			            helb.setText(dc.getHelbidea());
			            tele.setText(Integer.toString(dc.getTelefonoa()));  
			            aseg.setSelectedItem(dc.getAseguruTipoa());
					}
				}
			}
		});
		
		btnEguneratu = new JButton("Eguneratu");
		btnEguneratu.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				if (!zerbaitIdatziDu()) {

						nan.setEnabled(false);
					try {
						beze.bezAldatu(nan.getText(),
								izena.getText(), abi.getText(), helb.getText(),
								Integer.parseInt(tele.getText()),
								(String)aseg.getSelectedItem());
					} catch (NumberFormatException e) {
						JOptionPane.showMessageDialog(null,
								"Zenbakiak sartu!", "Oker",
								JOptionPane.ERROR_MESSAGE);
						e.printStackTrace();
					} catch (SQLException e) {
						JOptionPane.showMessageDialog(null,
								"Ezin izan da aldatu bezeroa", "Oker",
								JOptionPane.ERROR_MESSAGE);
						e.printStackTrace();
					}
					bm.init();
					table.updateUI();
					eremuakGarbitu();
					ezarri(false);
					btnBerria.setEnabled(true);

				}
			}
		});

		ajj.add(btnEguneratu);

		btnKendu = new JButton("Kendu");
		btnKendu.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				if (!zerbaitIdatziDu()) {
					try {
						beze.bezEzabatu(nan.getText());
					}
					catch (SQLException e) {
						JOptionPane.showMessageDialog(null,
								"Ezin izan da sortu bezeroa", "",
								JOptionPane.INFORMATION_MESSAGE);
						e.printStackTrace();
					}
					bm.init();
					table.updateUI();
					eremuakGarbitu();
					ezarri(false);
					btnBerria.setEnabled(true);
				}
			}
		});

		ajj.add(btnKendu);

		btnEzeztatu = new JButton("Ezeztatu");
		btnEzeztatu.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				ezarri(false);
			       btnBerria.setEnabled(true);
			       eremuakGarbitu();
			}
		});
		
		ajj.add(btnEzeztatu);

		JScrollPane scrollPane = new JScrollPane(table,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
		scrollPane.setPreferredSize(new Dimension(600, 90));
		scrollPane.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent arg0) {
				if (table.getRowCount() > 0 && table.getSelectedRow() != -1) {
					btnEguneratu.setEnabled(true);
					btnBerria.setEnabled(false);
					btnGorde.setEnabled(false);
					btnKendu.setEnabled(true);
					btnEzeztatu.setEnabled(true);
					Bezero dc = bm.getFila(table.getSelectedRow());
					nan.setText(dc.getNAN());
					izena.setText(dc.getIzena());
					abi.setText(dc.getAbizenak());
					helb.setText(dc.getHelbidea());
					tele.setText(Integer.toString(dc.getTelefonoa()));
					aseg.setSelectedItem(dc.getAseguruTipoa());
				}
			}
		});
		
		aux.add(scrollPane,BorderLayout.CENTER);
		panel.add(aux);
		
				
		btnGorde.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				if (!zerbaitIdatziDu()) {
					try {
						beze.bezSortu(nan.getText(),
								izena.getText(), abi.getText(), helb.getText(),
								Integer.parseInt(tele.getText()),
								(String)aseg.getSelectedItem());
					} catch (NumberFormatException e) {
						JOptionPane.showMessageDialog(null,
								"Sartu zenbakiak telefono eremuan", "",
								JOptionPane.INFORMATION_MESSAGE);
						e.printStackTrace();
					} catch (SQLException e) {
						JOptionPane.showMessageDialog(null,
								"Ezin izan da sortu bezeroa", "",
								JOptionPane.INFORMATION_MESSAGE);
						e.printStackTrace();
					}
					bm.init();
					table.updateUI();
					eremuakGarbitu();
					ezarri(false);
					btnBerria.setEnabled(true);
				} else
					JOptionPane.showMessageDialog(null,
							"Ondo sortu da bezeroa", "",
							JOptionPane.INFORMATION_MESSAGE);
			}

		});
		btnBilatu.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				if (!bil.getText().isEmpty()) {// hutsik
					bm.init2(aukeratu.getSelectedIndex() + 1, bil.getText());
					table.updateUI();				
				}else{JOptionPane.showMessageDialog(null,
						"Sartu zerbait zuriunetan", "",
						JOptionPane.INFORMATION_MESSAGE); }
			}
		});
				
		//behekoa
		JPanel behekoa = new JPanel();
		FlowLayout flowLayout = (FlowLayout) behekoa.getLayout();
		flowLayout.setAlignment(FlowLayout.CENTER);
		behekoa.setBackground(SystemColor.activeCaption);
		atzera= new JButton("Atzera");
		atzera.setFont(new Font("Arial", Font.PLAIN, 14));
		behekoa.add(atzera);
		add(behekoa, BorderLayout.SOUTH);
		atzera.addActionListener(new ActionListener() {			
			@Override
			public void actionPerformed(ActionEvent arg0) {
				itzuliInterfazea.itzuliLehenPanela();
			}
		});

	}

	private void ezarri(boolean opcion)
    {
        btnBerria.setEnabled(opcion);
        btnEguneratu.setEnabled(opcion);
        btnKendu.setEnabled(opcion); 
        btnEzeztatu.setEnabled(opcion);
        btnGorde.setEnabled(opcion);
    }
	
	private boolean zerbaitIdatziDu()
    {
        if(izena.getText().isEmpty()&&nan.getText().isEmpty()&&abi.getText().isEmpty()&&helb.getText().isEmpty() &&tele.getText().isEmpty())
           return true;
        else
            return false;
    }
	public void eremuakGarbitu() {
		izena.setText("");
		abi.setText("");
		nan.setText("");
		helb.setText("");
		tele.setText("");
		aseg.setSelectedIndex(0);	
		bm.init();
		
	}}
